package com.xju.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.xju.entity.Major;

import static com.xju.util.DBUtil.getConnection;

public class MajorDaoImpl implements MajorDao {
    @Override
    public List<Major> findMajorsByCollegeId(Integer collegeId) {
        String sql = "SELECT * FROM major WHERE college_id = ? ORDER BY major_name";
        List<Major> majors = new ArrayList<>();

        try (Connection conn = getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, collegeId);
            ResultSet rs = pstmt.executeQuery();

            while (rs.next()) {
                Major major = new Major();
                major.setMajorId(rs.getInt("major_id"));
                major.setMajorName(rs.getString("major_name"));
                major.setCollegeId(rs.getInt("college_id"));
                majors.add(major);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return majors;
    }

    @Override
    public List<Major> findMajorsByName(String name) {
        String sql = "SELECT * FROM major WHERE major_name LIKE ? ORDER BY major_name";
        List<Major> majors = new ArrayList<>();

        try (Connection conn = getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, "%" + name + "%");
            ResultSet rs = pstmt.executeQuery();

            while (rs.next()) {
                Major major = new Major();
                major.setMajorId(rs.getInt("major_id"));
                major.setMajorName(rs.getString("major_name"));
                major.setCollegeId(rs.getInt("college_id"));
                majors.add(major);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return majors;
    }
}
